package com.kaifamiao.www.ioDemo.do0921;

import java.io.*;

public class Work {
    public static void main(String[] args) {
        Work work = new Work();
        File file = new File("E:\\kaifamiao\\workspace\\idea--space\\html\\安全\\bofangqi\\gequ\\古巨基 - 匆匆那年 .mp3");
        long size = 1024*1024;//每个文件最大体积
        File file1 = new File("E:\\kaifamiao\\workspace\\idea--space\\io\\gequ");
        int n = work.split(file,size,file1);
        System.out.println(n);
        File dir = new File("E:\\kaifamiao\\workspace\\idea--space\\io\\gequ");//存已拆分文件目录
        File target = new File("E:\\kaifamiao\\workspace\\idea--space\\io\\匆匆那年.mp3");//合并后的文件存放目录
        long join = work.join(dir, target);
        System.out.println(join);
    }

        public int split(final File original,final long size,final File directory){
            int n=0;
            if(original.isFile()){
                if (directory.isDirectory()){
                    try ( FileInputStream fis = new FileInputStream(original);
                          BufferedInputStream bis = new BufferedInputStream(fis);
                    ){
                        int c = -1;
                        byte[] bytes = new byte[(int) size];
                        while ((c = bis.read(bytes))!=-1){
                            FileOutputStream fos = new FileOutputStream(new File(directory,n+".txt"));
                            fos.write(bytes,0,c);
                            n++;
                        }

                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return n;
        }
        /*** 将指定目录中的多个文件片段依次序合并到同一个文件中，并返回合并后的文件体积
         * @param dir 存放文件片段的目录(即拆分文件后的N个小文件的存放目录)
         * @param target 表示合并后的文件的存放路径
         * @return 返回合并后的文件体积
         */
        public long join(final File dir, final File target) {
            long size = 0 ; // 声明用于统计合并后的文件体积的变量
            File[] files= dir.listFiles();

            int len = 0;
            byte[] bytes = new byte[1024];
            try {
                FileOutputStream fos = new FileOutputStream(target);
                for (File file:files){
                    FileInputStream fis = new FileInputStream(file);
                    while ((len=fis.read())!=-1){
                        fos.write(bytes,0,len);
                    }
                }
                return target.length();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return size ; // 返回合并后的文件体积

        }

}
